.DEFAULT_GOAL := help
ENV_NAME ?= ./env
CONDA    ?= conda

PYTHON  ?= $(CONDA) run --no-capture-output -p $(ENV_NAME) python
PYTEST  ?= $(PYTHON) -m pytest

# Enables `make test tests/foo.py`; do NOT combine with other targets
# (e.g. `make test test-coverage`) — they'll be passed as pytest paths.
TEST_TARGET := $(filter-out test, $(MAKECMDGOALS))

.PHONY: help setup clean-setup test test-coverage install-dev which-python conda-build

which-python: ## Show Python executable being used (for debugging)
	@echo "PYTHON = $(PYTHON)"
	@$(PYTHON) -c "import sys; print('sys.executable =', sys.executable)"

setup: ## Create or update the conda-popcorn environment
	@echo "Setting up the conda-popcorn environment: $(ENV_NAME)"
	@if [ -d "$(ENV_NAME)" ]; then \
		echo "Environment exists, updating…"; \
		$(CONDA) env update -p $(ENV_NAME) -f environment.yml --prune; \
	else \
		echo "Environment not found, creating…"; \
		$(CONDA) env create -p $(ENV_NAME) -f environment.yml; \
	fi
	@echo "Installing package in development mode…"
	$(CONDA) run --no-capture-output -p $(ENV_NAME) pip install --no-deps -e .
	@echo "Done. Activate with: conda activate $(ENV_NAME)"

clean-setup: ## Remove the conda-popcorn environment
	@echo "Removing the conda-popcorn environment: $(ENV_NAME)"
	-$(CONDA) env remove -p $(ENV_NAME) -y
	@echo "Done."

install-dev: ## Install package in development mode into the current env
	$(CONDA) run --no-capture-output -p $(ENV_NAME) pip install --no-deps -e .

test: ## Run a file/dir (make test tests/test-file.py) or all tests
	$(PYTEST) -s -vvv $(if $(TEST_TARGET), $(TEST_TARGET), $(ARGS))

test-coverage: ## Run tests with a coverage report
	$(PYTEST) -s -vvv --cov=anaconda_popcorn --cov-report=term-missing --cov-fail-under=90 $(ARGS)

conda-build: ## Build the conda package into dist/
	@echo "Building conda package…"
	$(CONDA) run --no-capture-output -p $(ENV_NAME) \
		conda-build recipe/ --output-folder ./dist
	@echo "Artifact: dist/noarch/anaconda-popcorn-*.conda"

help: ## List available targets
	@awk 'BEGIN {FS = ":.*## "}; /^[a-zA-Z0-9_.-]+:.*## / {printf "  \033[36m%-20s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)

# Only suppress unknown-target errors when `test` is being invoked
ifneq ($(filter test, $(MAKECMDGOALS)),)
%:
	@:
endif